/*
// 基于准备好的dom，初始化echarts实例
var myChart = echarts.init(document.getElementById('main'));

// 指定图表的配置项和数据
var option = {
    title: {
        text: 'ECharts 入门示例'
    },
    tooltip: {},
    legend: {
        data: ['销量']
    },
    xAxis: {
        data: ["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"]
    },
    yAxis: {},
    series: [{
        name: '销量',
        type: 'bar',
        data: [5, 20, 36, 10, 10, 20]
    }]
};

// 使用刚指定的配置项和数据显示图表。
myChart.setOption(option);
*/
function initQueryDate() {
    var consultDay = {
        elem: "#consultDay",
        value: new Date(),
        btns: ['now', 'confirm'],
        max: 0,
        /* Object
         date: 22
         hours: 0
         minutes: 0
         month: 9
         seconds: 0
         year: 2017*/
        done: function (value, date) {
            //选完基准日期后查询
            initPeriodQuery();
        }
    };

    laydate.render(consultDay);
}


$(function () {
    var urlArr = [];
    urlArr.push("/api/statistics/consultOpentimes"); //统计打开次数
    urlArr.push("/api/statistics/countMember");//统计会员(总和月新增，分体验彩虹)
    urlArr.push("/api/statistics/consultOrderMoney");//统计当天、当月订单交易总额
    urlArr.push("/api/statistics/calculateOrdersAmount");//统计当日、当月下单量和支付量
    urlArr.push("/api/statistics/calculateGrossProfit");//统计当天、当月毛利润
    urlArr.push("/api/statistics/consultReturnSum");//统计当天、当月返现总额
    for (var zzUrl of urlArr) {
        assignStatistics(zzUrl);
    }
    addYears();
    init();
    //laydate和表格查询初始化，在laydate空间初始化完回调中初始化查询
    initQueryDate();
    initOpenPeriod();
    var newDate = new Date();
    newDate.getDate();
    var today = newDate.getFullYear() + "-" + (newDate.getMonth() + 1) + "-" + newDate.getDate();
    query(today, 1);
});

//共用异步查值赋值
function assignStatistics(url) {
    $.ajax({
        type: "get",
        url: urlcore + url,
        dataType: "json",
        contentType: "application/json;charset=utf-8",
        success: function (cbdata) {
            var data = cbdata.data;
            console.log(data);
            //将span的id设置为和data中的属性名一样，就可以通过属性名批量设置文本值
            for (var zz in data) {
                assignSpanText(zz, data[zz]);
            }
        },
        error: function (data) {
            alert("error");
        }
    });
}

//span text赋值
function assignSpanText(domId, value) {
    if (!isNaN(value)) {
        //百分比先乘100
        if (domId.indexOf("ConvertionRate")>-1) {
            value = (value * 100).toFixed(2);
        } else {
            //如果是件数人次等就取原来的整数，小数过来的保留一位小数
            if (value.toString().split(".").length > 1) {
                value = value.toFixed(1)
            }
        }
        $('#' + domId).text(value);
    }
}

// 中间数据表格条件查询
function initPeriodQuery() {
    var queryDate = $("#consultDay").val();
    //1 日、2 周、3 月、4 年
    var queryPeriod = $("#consultDateRange").val();
    if ("" == queryDate || "" == queryPeriod) {
        return
    }
    query(queryDate, queryPeriod);
}

function query(queryDate, queryPeriod) {
    $.ajax({
        url: urlcore + "/api/statistics/consultPeriodStatistics",
        type: "get",
        data: {queryDate: queryDate, queryPeriod: queryPeriod},
        dataType: 'json',
        contentType: "application/json;charset=utf-8",
        async: false,
        success: function (data) {
            if (data.success == true) {
                var cbdata = data.data;
                console.log(cbdata);
                var payMap = cbdata.payMap;
                var orderMap = cbdata.orderMap;
                //将td的id设置为和data中的属性名一样，就可以通过属性名批量设置文本值
                for (var zz in cbdata) {
                    if (zz != "payMap" && zz != "orderMap") {
                        assignSpanText(zz, cbdata[zz]);
                    }
                }
                for (var zz in payMap) {
                    assignSpanText(zz, payMap[zz]);
                }
                for (var zz in orderMap) {
                    assignSpanText(zz, orderMap[zz]);
                }
            }
        },
        error: function (data) {
            console.log("initPeriodQuery:error");
        }
    });
}

function init() {
    //获取年份
    var year = $('#year').val();
    //获取信息列表
    $.ajax({
        url: urlcore + "/api/statistics/consultOrderStatistics?year=" + year,
        type: "get",
        dataType: 'json',
        contentType: "application/json;charset=utf-8",
        async: false,
        success: function (data) {
            if (data.success == true) {

                // outMoneys = data.data.outMoneys;
                // backMoneys = data.data.backMoneys;
                var cbdata = data.data;
                console.log(cbdata);
                var monthTurnoverArr = [], createCountArr = [], payCountArr = [];
                for (var zz of cbdata) {
                    var pushValueMonthTurnover = 0;
                    var pushValueMonthCreateCount = 0;
                    var pushValueMonthPayCount = 0;
                    var pushValue = 0;
                    if (zz != null) {
                        if (undefined != zz.monthPayOrder) {
                            pushValueMonthTurnover = zz.monthPayOrder.monthPay;
                            pushValueMonthPayCount = zz.monthPayOrder.monthPayCount;
                        }
                        if (undefined != zz.monthOrderCount) {
                            pushValueMonthCreateCount = zz.monthOrderCount.monthOrderCount;
                        }
                    }
                    monthTurnoverArr.push(pushValueMonthTurnover);
                    createCountArr.push(pushValueMonthCreateCount);
                    payCountArr.push(pushValueMonthPayCount);
                }
                /*    var first = cbdata[0].monthPay;
                    var second = cbdata[1].monthPay;;
                    var third = cbdata[2].monthPay;;
                    var fourth = cbdata[3].monthPay;;
                    var fifth = cbdata[4].monthPay;;
                    var sixth = cbdata[5].monthPay;;
                    var seventh = cbdata[6].monthPay;;
                    var eighth = cbdata[7].monthPay;;
                    var ninth = cbdata[8].monthPay;;
                    var tenth = cbdata[9].monthPay;;
                    var eleven = cbdata[10].monthPay;;
                    var twelve = cbdata[11].monthPay;;

                    var firsts = cbdata[0].monthPayCount;
                    var seconds = cbdata[1].monthPayCount;
                    var thirds = cbdata[2].monthPayCount;
                    var fourths = cbdata[3].monthPayCount;
                    var fifths = cbdata[4].monthPayCount;
                    var sixths = cbdata[5].monthPayCount;
                    var sevenths = cbdata[6].monthPayCount;
                    var eighths = cbdata[7].monthPayCount;
                    var ninths = cbdata[8].monthPayCount;
                    var tenths =cbdata[9].monthPayCount;
                    var elevens =cbdata[10].monthPayCount;
                    var twelves =cbdata[11].monthPayCount;*/


                var myChart = echarts.init(document.getElementById('main'));
                // 指定图表的配置项和数据
                option = {
                    title: {
                        text: '月交易额、下单量统计'
                    },
                    tooltip: {
                        trigger: 'axis',
                        axisPointer: {            // 坐标轴指示器，坐标轴触发有效
                            type: 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
                        }
                    },
                    legend: {
                        data: ['月交易总额', '月下单人数', '月支付人数']
                    },
                    grid: {
                        left: '3%',
                        right: '4%',
                        bottom: '3%',
                        containLabel: true
                    },
                    xAxis: [
                        {
                            type: 'category',
                            data: ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月']
                        }
                    ],
                    yAxis: [
                        {
                            type: 'value',
//		                name:'万'
                        }
                    ],
                    series: [
                        {
                            name: '月交易总额',
                            type: 'bar',
                            // data:[first,second,third,fourth,fifth,sixth,seventh,eighth,ninth,tenth,eleven,twelve]
                            data: monthTurnoverArr,
                            label: {
                                normal: {
                                    show: true,
                                    position: "top",
                                    formatter: function (params) {
                                        params.data = params.data == 0 ? "" : params.data;
                                        return params.data;
                                    }
                                }
                            }
                        },
                        {
                            name: '月下单人数',
                            type: 'bar',
                            // data:[firsts,seconds,thirds,fourths,fifths,sixths,sevenths,eighths,ninths,tenths,elevens,twelves]
                            data: createCountArr,
                            label: {
                                normal: {
                                    show: true,
                                    position: "top",
                                    formatter: function (params) {
                                        params.data = params.data == 0 ? "" : params.data;
                                        return params.data;
                                    }
                                }
                            }
                        },
                        {
                            name: '月支付人数',
                            type: 'bar',
                            // data:[firsts,seconds,thirds,fourths,fifths,sixths,sevenths,eighths,ninths,tenths,elevens,twelves]
                            data: payCountArr,
                            label: {
                                normal: {
                                    show: true,
                                    position: "top",
                                    formatter: function (params) {
                                        params.data = params.data == 0 ? "" : params.data;
                                        return params.data;
                                    }
                                }
                            }
                        }


                    ]
                };

                // 使用刚指定的配置项和数据显示图表。
                myChart.setOption(option);


            } else if (data.code == 'OVERTIME') {
                var thisUrl = window.location.href;
                if (thisUrl.indexOf('login.html') <= -1) {
                    top.window.location.href = "../login.html";
                }

            } else {
            }

        },
        error: function () {
            alert("error");
        }
    });


}

//统计访问时间段
function initOpenPeriod() {
    $.ajax({
        url: urlcore + "/api/statistics/consultOpenPeriod",
        type: "get",
        dataType: 'json',
        contentType: "application/json;charset=utf-8",
        async: false,
        success: function (data) {
            if (data.success == true) {

                // outMoneys = data.data.outMoneys;
                // backMoneys = data.data.backMoneys;
                var cbdata = data.data;
                var list = cbdata.openPeriods;
                console.log(cbdata);
                var openPeriodArr = [];
                var openPeriodPercentArr = [];
                var sumTimes = cbdata.sumTimes;
                for (var zz of list) {
                    openPeriodArr.push(zz.openTimes);
                    // var percent=((zz.openTimes)*100/sumTimes).toFixed(1).toString()+"%";
                    var percent = ((zz.openTimes) / sumTimes).toFixed(2);
                    openPeriodPercentArr.push(percent);
                }
                // 基于准备好的dom，初始化echarts实例
                var openPeriodChart = echarts.init(document.getElementById('openPeriod'));

                // 指定图表的配置项和数据
                var option = {
                    title: {
                        text: '访问时间段分布统计'
                    },
                    tooltip: {
                        trigger: 'axis',
                        axisPointer: {            // 坐标轴指示器，坐标轴触发有效
                            type: 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
                        }
                    },
                    legend: {
                        data: ['访问人次', '时段占比']
                    },
                    grid: {
                        left: '3%',
                        right: '4%',
                        bottom: '3%',
                        containLabel: true
                    },
                    xAxis: {
                        data: ["0时-1时", "1时-2时", "2时-3时", "3时-4时", "4时-5时", "5时-6时", "6时-7时", "7时-8时", "8时-9时", "9时-10时", "10时-11时", "11时-12时",
                            "12时-13时", "13时-14时", "14时-15时", "15-16时", "16时-17时", "17时-18时", "18时-19时", "19时-20时", "20时-21时", "21时-22时", "22时-23时", "23时-24时"]
                    },
                    yAxis: [
                        {
                            type: 'value',
                        }
                    ],
                    series: [{
                        name: '访问人次',
                        type: 'bar',
                        data: openPeriodArr,
                        label: {
                            normal: {
                                show: true,
                                position: "top",
                                formatter: function (params) {
                                    params.data = params.data == 0 ? "" : params.data;
                                    return params.data;
                                }
                            }
                        }
                    }, {
                        name: '时段占比',
                        type: 'bar',
                        data: openPeriodPercentArr,
                        label: {
                            normal: {
                                show: true,
                                position: "top",
                                formatter: function (params) {
                                    if (params.data == 0)
                                        return "";
                                    return (params.data * 100).toFixed(1) + "%";
                                }
                            }
                        }
                    }]
                };

                // 使用刚指定的配置项和数据显示图表。
                openPeriodChart.setOption(option);
            } else if (data.code == 'OVERTIME') {
                var thisUrl = window.location.href;
                if (thisUrl.indexOf('login.html') <= -1) {
                    top.window.location.href = "../login.html";
                }

            } else {
            }

        },
        error: function () {
            alert("error");
        }
    });

}


//填充年份下拉
function addYears() {
    var myDate = new Date();
    year = myDate.getFullYear();
    var year1 = year - 1;
    var year2 = year - 2;
    var year3 = year - 3;
    var html = "<option value='" + year + "'>" + year + "年</option>";
    html = html + "<option value='" + year1 + "'>" + year1 + "年</option>";
    html = html + "<option value='" + year2 + "'>" + year2 + "年</option>";
    html = html + "<option value='" + year3 + "'>" + year3 + "年</option>";

    $('#year').append(html);
}


/*
$(document).ready(function () {
	$.ajax({
        url:  urlcore + "/api/cashRecord/sum",
        type: "get",
        contentType: "application/json;charset=utf-8",
        dataType: "json",
        success:function(data){
            if (data.success == true) {
				$('#allSum').html(data.data[0].allSum);
				$('#allSumByMonth').html(data.data[1].allSumByMonth);
				$('#allSumByDay').html(data.data[2].allSumByDay);
				$('#ordersSum').html(data.data[3].ordersSum);
				$('#ordersSumByMonth').html(data.data[4].ordersSumByMonth);
				$('#ordersSumByDay').html(data.data[5].ordersSumByDay);
            } else if (data.code == 'OVERTIME') {
                var thisUrl = window.location.href;
                if (thisUrl.indexOf('login.html') <= -1) {
                    top.window.location.href = "login.html";
                }
            } else {
                alert(data.msg);
            }

        },
        error: function() {
           
        }

    });   
		
});

function echart(){
	var sumType=$("#sumType").val();
	var timeType=$("#timeType").val();
	//拿到总额数据
	var da='';
	$.ajax({
        url:  urlcore + "/api/cashRecord/barSum?sumType="+sumType+"&timeType="+timeType,
        type: "get",
        contentType: "application/json;charset=utf-8",
        dataType: "json",
        async: false,
        success:function(data){
            if (data.success == true) {
             da=data.data;
            } else if (data.code == 'OVERTIME') {
                var thisUrl = window.location.href;
                if (thisUrl.indexOf('login.html') <= -1) {
                    top.window.location.href = "login.html";
                }
            } else {
                alert(data.msg);
            }

        },
        error: function() {
            alert("error");
        }

    });
    
    var x="",y="";
    if(timeType==1){
    	 x = [GetDateStr(-6),GetDateStr(-5),GetDateStr(-4),GetDateStr(-3),GetDateStr(-2),GetDateStr(-1),GetDateStr(0)];
    	 y=[da[6].sum,da[5].sum,da[4].sum,da[3].sum,da[2].sum,da[1].sum,da[0].sum]
    }
	if(timeType==2){
		x=['1月','2月','3月','4月','5月','6月','7月','8月','9月','10月','11月','12月'];
		y=[da[0].sum,da[1].sum,da[2].sum,da[3].sum,da[4].sum,da[5].sum,da[6].sum,da[7].sum,da[8].sum,da[9].sum,da[10].sum,da[11].sum];
	}
	if(timeType==3){
		x=['1季度','2季度','3季度','4季度'];
		y=[da[0].sum,da[1].sum,da[2].sum,da[3].sum];
	}
	if(timeType==4){
		x=[GetYearStr(-4),GetYearStr(-3),GetYearStr(-2),GetYearStr(-1),GetYearStr(0)];
		y=[da[4].sum,da[3].sum,da[2].sum,da[1].sum,da[0].sum];
	}
    // 路径配置
    require.config({
        paths: {
            echarts: 'http://echarts.baidu.com/build/dist'
        }
    });
    
    // 使用
    require(
        [
            'echarts',
            'echarts/chart/bar' // 使用柱状图就加载bar模块，按需加载
        ],
        function (ec) {
            // 基于准备好的dom，初始化echarts图表
            var myChart = ec.init(document.getElementById('main')); 
            
            var option = {
                tooltip: {
                    show: true
                },
                legend: {
                    data:['']
                },
                xAxis : [
                    {
                        type : 'category',
                        data : x
                    }
                ],
                yAxis : [
                    {
                        type : 'value'
                    }
                ],
                series : [
                    {
                        "name":"数量",
                        "type":"bar",
                        "data":y
                    }
                ]
            };
    
            // 为echarts对象加载数据 
            myChart.setOption(option); 
        }
    );
}

//获取最近一周日期
function GetDateStr(AddDayCount) { 
	var dd = new Date(); 
	dd.setDate(dd.getDate()+AddDayCount);//获取AddDayCount天后的日期 
	var y = dd.getFullYear(); 
	var m = dd.getMonth()+1;//获取当前月份的日期 
	var d = dd.getDate(); 
	return y+"-"+m+"-"+d; 
} 

//获取最近五年
function GetYearStr(AddDayCount) { 
	var dd = new Date(); 
	dd.setFullYear(dd.getFullYear()+AddDayCount);//获取AddDayCount天后的日期 
	var y = dd.getFullYear(); 
	return y; 
} 

//下拉框
function sumType(){
    $("#sumType").change(function () {
   		echart();
	});
}

function timeType(){
    $("#timeType").change(function () {
   		echart();
	});
}*/
